package com.jinzhi.jinzhidata.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {

    //获取Cookie值
    public static String getCookieValue(HttpServletRequest httpServletRequest, String name) {
        Cookie[] cookies = httpServletRequest.getCookies();
        if (null == cookies || cookies.length == 0) {
            return null;
        } else {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(name)) {
                    return cookie.getValue();
                }
            }
            return null;
        }
    }

    //获取Cookie
    public static Cookie getCookie(HttpServletRequest httpServletRequest, String name) {
        Cookie[] cookies = httpServletRequest.getCookies();
        if (null == cookies || cookies.length == 0) {
            return null;
        } else {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(name)) {
                    return cookie;
                }
            }
            return null;
        }
    }

    //添加Cookie
    public static void addCookie(HttpServletResponse httpServletResponse, String name, String value) {
        Cookie cookie = new Cookie(name, value);
        cookie.setMaxAge(7 * 24 * 60 * 60);
        cookie.setPath("/");
        httpServletResponse.addCookie(cookie);
    }

    //修改Cookie
    public static void modifyCookie(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String name, String value) {
        Cookie cookie = getCookie(httpServletRequest, name);
        if (null != cookie) {
            cookie.setValue(value);
            cookie.setMaxAge(7 * 24 * 60 * 60);
            cookie.setPath("/");
            httpServletResponse.addCookie(cookie);
        }
    }

    //删除Cookie
    public static void deleteCookie(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String name) {
        Cookie cookie = getCookie(httpServletRequest, name);
        if (cookie != null) {
            cookie.setValue(null);
            cookie.setMaxAge(0);
            cookie.setPath("/");
            httpServletResponse.addCookie(cookie);
        }
    }
}
